
package flc.ast.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;

import java.util.List;

import flc.ast.AppConfig;
import flc.ast.R;
import flc.ast.adapter.DeviceAdapter;
import flc.ast.databinding.DialogDeviceBinding;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseSmartDialog;

public class DeviceDialog extends BaseSmartDialog<DialogDeviceBinding> implements View.OnClickListener {

    private CastScreenManager mCastScreenManager;
    private boolean isSearch = false;
    private DeviceAdapter deviceAdapter;
    private int oldPosition;

    public DeviceDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean canceledOnTouchOutside() {
        return true;
    }

    @Override
    protected int getGravity() {
        return Gravity.BOTTOM;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_device;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (isSearch) return;
        isSearch = true;
        mCastScreenManager.startBrowse();
    }

    @Override
    protected void initView(View view) {
        mDataBinding.tvCancel.setOnClickListener(this);
        mDataBinding.tvConfirm.setOnClickListener(this);
        mDataBinding.tvDeviceNoData.setText(getContext().getString(R.string.search_ing));

        mDataBinding.rvDeviceList.setLayoutManager(new LinearLayoutManager(getContext()));
        deviceAdapter = new DeviceAdapter();
        mDataBinding.rvDeviceList.setAdapter(deviceAdapter);
        deviceAdapter.addChildClickViewIds(R.id.ivDeviceItemSel);
        deviceAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (view.getId() == R.id.ivDeviceItemSel) {
                    if (deviceAdapter.getItem(position).isConnect()) {
                        Content.IsConnect = false;
                        deviceAdapter.getItem(position).setConnect(false);
                        deviceAdapter.notifyDataSetChanged();
                        mCastScreenManager.disConnect();
                        Content.ConnectName = "";
                    } else {
                        Content.IsConnect = true;
                        deviceAdapter.getItem(oldPosition).setConnect(false);
                        oldPosition = position;
                        deviceAdapter.getItem(position).setConnect(true);
                        deviceAdapter.notifyDataSetChanged();
                        mCastScreenManager.connect(deviceAdapter.getItem(position));
                        Content.ConnectName = deviceAdapter.getItem(position).getName();
                    }
                    if (listener != null) {
                        listener.clickItem();
                    }
                }
            }
        });
        registerScreen();
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tvCancel) {
            dismiss();
        } else if (id == R.id.tvConfirm) {
            dismiss();
        }
    }

    //注册投屏
    private void registerScreen() {
        CastScreenManager.init(AppConfig.TEST_APP_ID, AppConfig.TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {
            @Override
            public void onInit(boolean success) {
                isSearch = true;
                if (success) {
                    Content.IsInit = true;
                    mCastScreenManager.startBrowse();
                } else {
                    Content.IsInit = false;
                }
            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                isSearch = false;
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (deviceAdapter != null) {
                        mDataBinding.tvDeviceNoData.setVisibility(View.GONE);
                        mDataBinding.rvDeviceList.setVisibility(View.VISIBLE);
                        deviceAdapter.setList(list);
                        //回显连接状态
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(Content.ConnectName)) {
                                list.get(i).setConnect(true);
                            }
                        }
                        deviceAdapter.notifyDataSetChanged();
                    } else {
                        mDataBinding.tvDeviceNoData.setText(getContext().getString(R.string.not_search_pro_device));
                        mDataBinding.tvDeviceNoData.setVisibility(View.VISIBLE);
                        mDataBinding.rvDeviceList.setVisibility(View.GONE);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showLong(R.string.search_over);
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showLong(R.string.auth_def);
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = getContext().getString(R.string.no_agreement);
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = getContext().getString(R.string.lelian_agreement);
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = getContext().getString(R.string.dlna_agreement);
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = getContext().getString(R.string.im_agreement);
                        break;
                }
                if (lelinkServiceInfo.getName() != null && !TextUtils.isEmpty(lelinkServiceInfo.getName())) {
                    Content.IsConnect = true;
                    Content.ConnectName = lelinkServiceInfo.getName();
                } else {
                    Content.IsConnect = false;
                    Content.ConnectName = "";
                }
                ToastUtils.showLong(getContext().getString(R.string.conn_device) + lelinkServiceInfo.getName() + getContext().getString(R.string.agreement_to) + strProtocol);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                Content.IsConnect = false;
                String text = getContext().getString(R.string.break_device) + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + getContext().getString(R.string.wait_right);
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + getContext().getString(R.string.conn_refuse);
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + getContext().getString(R.string.saorao_request_over);
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + getContext().getString(R.string.black_list);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getContext().getString(R.string.conn_break);
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + getContext().getString(R.string.no_online);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getContext().getString(R.string.conn_def);
                            break;
                    }
                }
                ToastUtils.showLong(text);
            }
        });
        if (!Content.IsInit) {
            //showDialog(getString(R.string.init_ing));
            mCastScreenManager.init();
        }
    }


    private Ilistener listener;

    public void setListener(Ilistener listener) {
        this.listener = listener;
    }

    public interface Ilistener {
        void clickItem();
    }
}
